import {ConfigEnv, defineConfig, UserConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint';
import stylelintPlugin from 'vite-plugin-stylelint';
import {fileURLToPath, URL} from "node:url";
import {loadEnv} from 'vite';
import browserslist from 'browserslist'
import legacy from '@vitejs/plugin-legacy';
import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
// import { createHtmlPlugin } from 'vite-plugin-html';
// import { visualizer } from "rollup-plugin-visualizer";

const browserslistConfig = browserslist.loadConfig({ path: '.' })

export default defineConfig(
  ({mode}: ConfigEnv): UserConfig => {

    const env = loadEnv(mode, process.cwd());

    return {
      base: env.VITE_BASE_URL,
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
      },
      plugins: [
        vue(),
        eslintPlugin({
          include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue'],
          fix: true
        }),
        stylelintPlugin({
          files: ['src/**/*.{css,scss,less}'],
          fix: true,
          cache: true,
        }),
        legacy({
          targets: browserslistConfig,
        }),
        Components({
          resolvers: [AntDesignVueResolver()]
        })
        // createHtmlPlugin({
        //   template: './index.html',
        //   inject: {
        //     tags: [
        //       {
        //         injectTo: 'body',
        //         tag: 'script',
        //         attrs: {
        //           src: 'https://g.xxx.cn/@app/static/react@17.0.2,react-dom@17.0.2,react-router-dom@6.3.0,immer@9.0.15,axios@0.27.2,js-cookie@3.0.1.min.js',
        //           defer: true
        //         }
        //       },
        //     ]
        //   }}
        // ),
        // visualizer({
        //   open: true,
        // }),
      ],
      server: {
        host: '0.0.0.0',
        port: Number(env.VITE_PROXY_SERVE_PORT),
        open: true,
        proxy: {
          '/api': {
            target: env.VITE_PROXY_SERVE_TARGET,
            changeOrigin: true,
            rewrite: path =>
              path.replace(new RegExp('^/api'), '')
          },
        }
      },
      build: {
        sourcemap: true,
        outDir: "dist",
        chunkSizeWarningLimit: 500,
        rollupOptions: {
          output: {
            chunkFileNames: "assets/js/[name]-[hash].js",
            entryFileNames: "assets/js/[name]-[hash].js",
            assetFileNames:"assets/[ext]/name-[hash].[ext]",
            manualChunks: {
              vue: ['vue', 'pinia', 'vue-router'],
              ant: ['ant-design-vue']
            },
          }
        }
      },
    }
  }
);
